package com.machuxin.course.patterns.single;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class TestSingle {


    public static void main(String[] args) throws Exception {
//        // 无聊情况下进行破坏
//        Class<?> clazz = Singleton3.class;
//        // 获取私有化构造方法
//        Constructor constructor = clazz.getDeclaredConstructor(null);
//        // 强制访问
//        constructor.setAccessible(true);
//        // 暴力初始化两次
//        Object o1 = constructor.newInstance();
//        Object o2 = constructor.newInstance();
//        System.out.println(o1);
//        System.out.println(o2);
//        System.out.println(o1 == o2);


//        Singleton3 singleton3 = Singleton3.getInstance();
//        System.out.println(singleton3);

//        Singleton4 s1 = null;
//        Singleton4 s2 = Singleton4.getInstance();
//
//        FileOutputStream fos = new FileOutputStream("Singleton4.obj");
//        ObjectOutputStream oos = new ObjectOutputStream(fos);
//        oos.writeObject(s2);
//        oos.flush();
//        oos.close();
//
//        FileInputStream fis = new FileInputStream("Singleton4.obj");
//        ObjectInputStream ois = new ObjectInputStream(fis);
//        s1 = (Singleton4) ois.readObject();
//        ois.close();
//
//        System.out.println(s1);
//        System.out.println(s2);
//        System.out.println(s1 == s2);


        Singleton5 s1 = null;
        Singleton5 s2 = Singleton5.getInstance();
        Object o1 = new TestSingle();
        s2.setData(o1);

        FileOutputStream fos = new FileOutputStream("Singleton4.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(s2);
        oos.flush();
        oos.close();
        FileInputStream fis = new FileInputStream("Singleton4.obj");
        ObjectInputStream ois = new ObjectInputStream(fis);
        s1 = (Singleton5) ois.readObject();
        ois.close();

        System.out.println(s1.getData());
        System.out.println(s2.getData());
        System.out.println(s2.getData() == s1.getData());
    }
}
